# ========================================
# 构建并推送 Docker 镜像到阿里云 ACR
# ========================================

param(
    [string]$Tag = 'latest',
    [switch]$NoCache
)

# 设置输出编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'Stop'

# 配置参数
$AcrRepo = 'crpi-j39i6g2qk4ln00fg.cn-chengdu.personal.cr.aliyuncs.com/testnamespace-zb'
$ImageName = 'mskml-web'

# 获取脚本所在目录（项目根目录）
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ScriptDir

if ([string]::IsNullOrWhiteSpace($Tag)) {
    $Tag = "latest"
}

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Build and Push Docker Image" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# ========================================
# 步骤 1: 构建 Docker 镜像
# ========================================
Write-Host "[1/4] Building Docker image..." -ForegroundColor Yellow
$LocalImage = "$ImageName" + ":" + $Tag
Write-Host "Image name: $LocalImage" -ForegroundColor Cyan
Write-Host "Build directory: $ScriptDir" -ForegroundColor Cyan
Write-Host ""

if ($NoCache) {
    docker build --no-cache -t $LocalImage .
} else {
    docker build -t $LocalImage .
}

if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Docker build failed!" -ForegroundColor Red
    exit 1
}

# 验证镜像是否存在
Start-Sleep -Seconds 1
$ImageCheck = docker images $ImageName --format "{{.Repository}}:{{.Tag}}" | Select-String -Pattern "^${ImageName}:${Tag}$"
if (-not $ImageCheck) {
    Write-Host "[ERROR] Image not found after build: $LocalImage" -ForegroundColor Red
    Write-Host "Current images:" -ForegroundColor Yellow
    docker images | Select-String $ImageName
    exit 1
}

Write-Host "[OK] Docker image build completed: $LocalImage" -ForegroundColor Green
Write-Host ""

# ========================================
# 步骤 2: 打标签
# ========================================
Write-Host "[2/4] Tagging image..." -ForegroundColor Yellow

$RemoteImage = $AcrRepo + "/" + $ImageName + ":" + $Tag
Write-Host "Local image: $LocalImage" -ForegroundColor Cyan
Write-Host "Remote image: $RemoteImage" -ForegroundColor Cyan
Write-Host ""

docker tag $LocalImage $RemoteImage

if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Docker tag failed!" -ForegroundColor Red
    Write-Host "Please check image name format" -ForegroundColor Red
    exit 1
}

Write-Host "[OK] Image tagged: $RemoteImage" -ForegroundColor Green
Write-Host ""

# ========================================
# 步骤 3: 推送到阿里云 ACR
# ========================================
Write-Host "[3/4] Pushing to Alibaba Cloud ACR..." -ForegroundColor Yellow
Write-Host "Remote image: $RemoteImage" -ForegroundColor Cyan
Write-Host ""
Write-Host "Pushing layers (this may take a while)..." -ForegroundColor Cyan
Write-Host ""

# 推送镜像，显示详细进度
docker push $RemoteImage

if ($LASTEXITCODE -ne 0) {
    Write-Host ""
    Write-Host "[ERROR] Docker push failed!" -ForegroundColor Red
    $LoginCmd = "Please login: docker login " + $AcrRepo
    Write-Host $LoginCmd -ForegroundColor Yellow
    exit 1
}

Write-Host ""
Write-Host "[OK] Image pushed successfully!" -ForegroundColor Green

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "[SUCCESS] Build and push completed!" -ForegroundColor Green
Write-Host "Image: $RemoteImage" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""

# ========================================
# 步骤 4: 清理本地镜像（可选）
# ========================================
Write-Host "[4/4] Cleaning up local images..." -ForegroundColor Yellow
Write-Host ""

# 删除远程标签的镜像
docker rmi $RemoteImage 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
    Write-Host "[OK] Removed remote tagged image: $RemoteImage" -ForegroundColor Green
}

# 删除本地镜像（可选，注释掉如果不想删除）
# docker rmi $LocalImage 2>&1 | Out-Null
# if ($LASTEXITCODE -eq 0) {
#     Write-Host "[OK] Removed local image: $LocalImage" -ForegroundColor Green
# }

Write-Host "[OK] Cleanup completed!" -ForegroundColor Green
Write-Host ""

Write-Host "========================================" -ForegroundColor Green
Write-Host "All operations completed successfully!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

